package br.brpv.silvestrin.vendas.manager;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import br.brpv.silvestrin.vendas.R;
import br.brpv.silvestrin.vendas.domain.*;
import br.brpv.silvestrin.vendas.listeners.MakeOrderQueryListener;
import br.brpv.silvestrin.vendas.util.ShowMessage;
import br.brpv.silvestrin.vendas.webservice.ServerConnection;

import java.util.ArrayList;


public class OrderManager implements MakeOrderQueryListener {
    private Activity mActivity;
    private Order order;

    private ArrayList<AddedItem> itemsToSend;
    private ArrayList<AddedItem> itemsSent;
    OrderManagerInterface orderManagerInterface;
    private AddedItem itemBeenSent;

    public OrderManager(Activity activity, OrderManagerInterface orderManagerInterface) {
        this.mActivity = activity;
        this.orderManagerInterface = orderManagerInterface;
    }

    public void initOrder(User user, CompanyParameters paramsCompany, String clientID, String establishmentId){
        order = new Order();

        order.setTpmnt("I");
        order.setId("0");
        order.setCompanyId(paramsCompany.getCompanyId());
        order.setClientId(clientID);
        order.setDateDeliver("");
        order.setStatus("1");
        order.setUserId(user.getId());
        order.setTypeDiscount("");
        order.setValueDiscount("0");
        order.setTypeAcresc("");
        order.setValueAcresc("0");
        order.setForn_id(paramsCompany.getTransporter());
        order.setTypeFrete(paramsCompany.getTransporterType());
        order.setValueFrete("0");
        order.setObsOrder("");
        order.setObsNotaFiscal("");
        order.setPor_id("0");
        order.setCondPaymentId("0");
        order.setPlacaId("0");
        order.setPlaca("");
        order.setTypeNotaFiscal("0");
        order.setHourInicial("");
        order.setHourFinal("");
        order.setEstablishmentId(establishmentId);
        order.setRepresentanteId("0");
        order.setOrdemCompra("");
        order.setPriceTableId(paramsCompany.getPriceTable());
        order.setDriverId("0");
        order.setDateExped("");
        order.setHourExped("");
        order.setAddressId("0");
        order.setLevaLote("0");
        order.setCPF("0");
        order.setName("");

        ServerConnection.initializeOrder(order, this);
    }
    public void setOrder(Order order){
        this.order = order;
    }

    public void removeItemFromOrder(String itemId){
        ServerConnection.performRemoveItemFromOrder(itemId, this);
    }

    public void addItemsToOrder(ArrayList<AddedItem> items){
        itemsToSend = items;
        itemsSent = new ArrayList<AddedItem>();
        sendNextItemToOrder();
    }

    public void addItemToOrder(Order order, AddedItem item){
        itemBeenSent = item;
        ServerConnection.performAddItemToOrder(order, item, this);
    }

    public void sendOrderToServer(){
        order.setStatus(String.valueOf(Order.STATUS_SAVE));
        ServerConnection.performMakeOrder(order, this);
    }

    public void sendOrderAndFinalize(){
        order.setStatus(String.valueOf(Order.STATUS_FINALIZE));
        ServerConnection.performMakeOrder(order, this);
    }

    public void finalizeOrder(String orderId){
        ServerConnection.finalizeOrder(orderId, String.valueOf(Order.STATUS_FINALIZE), this);
    }

    public void removeOrder(String orderId){
        ServerConnection.removeOrder(orderId,this);
    }

    private void sendNextItemToOrder(){
        if(itemsToSend != null && !itemsToSend.isEmpty()){
            AddedItem item = itemsToSend.get(0);
            ServerConnection.performAddItemToOrder(order, item, this);
        } else{
            //Quando acabou de incluir itens pega os valores
            orderManagerInterface.onItemsAdded(itemsSent);
            ServerConnection.getOrderValorBruto(order.getId(),OrderManager.this);
            ServerConnection.getOrderValorLiquido(order.getId(),OrderManager.this);
        }
    }

    public void getOrderValues(){
        ServerConnection.getOrderValorBruto(order.getId(),OrderManager.this);
        ServerConnection.getOrderValorLiquido(order.getId(),OrderManager.this);
    }

    @Override
    public void failedOnInitializeOrder(String s) {
        ShowMessage.alertDialog2(mActivity, R.string.message_initOrderFail, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mActivity.finish();
            }
        });
    }

    @Override
    public void OnWebServiceInitializeOrderReturn(int orderId) {
        order.setId(String.valueOf(orderId));
        order.setTpmnt("A"); //agora vai alterar o pedido e nao mais incluir
        orderManagerInterface.orderInitialized(order);
    }

    @Override
    public void failedOnRemoveOrder() {
    }

    @Override
    public void OnWebServiceRemoveOrderReturn(String resultString) {
        orderManagerInterface.orderRemoved(resultString);
    }


    @Override
    public void OnWebServiceMakeOrderReturn(int orderId) {
        if(Integer.valueOf(order.getStatus()) == Order.STATUS_FINALIZE) { //ja finalizou o pedido
            orderManagerInterface.orderFinalized(order);
        }else{
            order.setId(String.valueOf(orderId));
            order.setTpmnt("A"); //agora vai alterar o pedido e nao mais incluir
            orderManagerInterface.orderInitialized(order);
        }
    }

    @Override
    public void failedOnMakeOrder(String s) {
        ShowMessage.alertDialog2(getActivity(),
                mActivity.getResources().getString(R.string.makeorder_failonmakeorder) + s,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                                //mActivity.finish();
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                ServerConnection.performMakeOrder(order, OrderManager.this);
                                break;
                        }
                    }
                });
    }

    @Override
    public void OnWebServiceAddItemReturn(String itemId) {
        //AddedItem item = itemsToSend.remove(0);
        Toast.makeText(mActivity, itemBeenSent.getDescription(), 5);
        itemBeenSent.setTpmnt("A");
        itemBeenSent.setId(itemId);
        orderManagerInterface.onItemAdded(itemBeenSent);
        //itemsSent.add(itemBeenSent);
        //sendNextItemToOrder();
    }

    @Override
    public void failedOnAddItem() {
        ShowMessage.alertDialog2(getActivity(), R.string.makeorder_failonsenditem,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                                mActivity.finish();
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                sendNextItemToOrder();
                                break;
                        }
                    }
                });
    }

    @Override
    public void OnWebServiceValorBrutoReturn(String valorBruto) {
        orderManagerInterface.onValorBrutoReturn(valorBruto);
    }

    @Override
    public void failedOnRetriveValorBruto() {
    }

    @Override
    public void OnWebServiceValorLiquidoReturn(String valorLiquido) {
        orderManagerInterface.onValorLiquidoReturn(valorLiquido);
    }

    @Override
    public void failedOnRetriveValorLiquido() {
    }

    @Override
    public Context getActivity() {
        return mActivity;
    }

    @Override
    public void failedOnFinalizeOrder() {
        ShowMessage.alertDialog(mActivity,"Erro ao finalizar pedido!!\nProvavelmente está faltando parâmetros importantes.\nVocê deveria poder editar esse pedido, mas o sistema não permite.");
    }

    @Override
    public void OnWebServiceFinalizeOrderReturn(String message) {
         orderManagerInterface.orderFromSaveToFinalized(message);
    }

    @Override
    public void OnWebServiceRemoveItemReturn(String itemId) {
        orderManagerInterface.onItemRemoved(itemId);
    }

    public interface OrderManagerInterface {
        public void orderInitialized(Order order);
        public void orderFinalized(Order order);
        public void orderFromSaveToFinalized(String message);
        public void onValorBrutoReturn(String valorBruto);
        public void onValorLiquidoReturn(String valorLiquido);

        public void onItemsAdded(ArrayList<AddedItem> itemsSent);

        public void onItemRemoved(String itemId);
        public void onItemAdded(AddedItem item);

        public void orderRemoved(String resultString);
    }

}
